package com.pms.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pms.constant.MessageConstant;
import com.pms.dto.VehiclePageQueryDTO;
import com.pms.dto.VehicleSaveDTO;
import com.pms.entity.Owner;
import com.pms.entity.Vehicle;
import com.pms.exception.NotFoundException;
import com.pms.mapper.OwnerMapper;
import com.pms.mapper.VehicleMapper;
import com.pms.result.PageResult;
import com.pms.service.VehicleService;
import com.pms.vo.VehiclePageQueryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class VehicleServiceImpl implements VehicleService {

    @Autowired
    private VehicleMapper vehicleMapper;
    @Autowired
    private OwnerMapper ownerMapper;

    /**
     * 新增车辆
     * @param vehicleSaveDTO
     */
    public void save(VehicleSaveDTO vehicleSaveDTO) {
        Owner owner=ownerMapper.getByOwnerName(vehicleSaveDTO.getOwnerName());
        if(owner==null){
            throw new NotFoundException(MessageConstant.OWNER_NOT_EXIST);
        }

        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleSaveDTO,vehicle);
        vehicle.setOwnerId(owner.getId());

        vehicleMapper.save(vehicle);
    }

    /**
     * 车辆分页查询
     * @param vehiclePageQueryDTO
     * @return
     */
    public PageResult page(VehiclePageQueryDTO vehiclePageQueryDTO) {
        PageHelper.startPage(vehiclePageQueryDTO.getPage(), vehiclePageQueryDTO.getPageSize());
        Page<VehiclePageQueryVO> page=vehicleMapper.pageQuery(vehiclePageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            vehicleMapper.delete(id);
        }
    }
}
